package com.rinvay.asdownloader.service;

import java.util.ArrayList;

import com.rinvay.asdownloader.platform.logger.AndroidAppender;
import com.rinvay.asdownloader.platform.persistent.DownloadTaskDAO;
import com.rinvay.filedownload.FileDownloadManager;
import com.rinvay.filedownload.model.DownloadTask;
import com.rinvay.utils.logger.Appender;
import com.rinvay.utils.logger.Logger;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class DownloadService extends Service
{
    private static final String TAG = "DownloadService";

    private FileDownloadManager downloadMgr;

    public class DownloadBinder extends Binder
    {

        public FileDownloadManager getDownloadMgr() {
            return downloadMgr;
        }

    }

    public IBinder onBind(Intent intent) {
        Logger.info(TAG, " onBind");
        return new DownloadBinder();
    }

    public void onCreate() {
        super.onCreate();

        Logger.info(TAG, " onCreate");

        downloadMgr = new FileDownloadManager();
        downloadMgr.getResourceList().addAll(
                DownloadTaskDAO.getInstance().queryAllDownloadTask());

    }

    public void onDestroy() {
        Logger.info(TAG, " onDestroy");
        ArrayList<DownloadTask> taskes = downloadMgr.getResourceList();
        for(DownloadTask task: taskes) {
            if(!task.isTaskFinished()) {
                DownloadTaskDAO.getInstance().updateDownloadTask(task);
            }
        }
        super.onDestroy();
    }

}
